package com.tanhua.dubbo.server.service;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @ClassName :  IdService
 * @Author : Tenebrous
 * @Date: 2020/12/18 15:11
 * @Description : 自增长id  原理使用redis的自增长类型，时效增长id
 */
@Service
public class IdService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 生成自增长的id
     * @return   long
     */
    public Long createdId(String type, String objectId) {
        // 如果ObjectId已经存在，返回对应的id
        type = StringUtils.upperCase(type);
        String hashKey = "TANHUA_HASH_ID_" + type;
        if (this.redisTemplate.opsForHash().hasKey(hashKey, objectId)) {
            return Long.valueOf(this.redisTemplate.opsForHash().get(hashKey,objectId).toString());
        }
        String key = "TANHUA_ID" + type;
        Long id = this.redisTemplate.opsForValue().increment(key);
        // 将生成的id写入到hash表中
        this.redisTemplate.opsForHash().put(hashKey, objectId, id.toString());
        return id;
    }
}
